<template>
  <div class="pratice">
    <div class="mains_contain">
      <div class="mains_contains">
        <ElementJson
          ref="elementJson"
          class="JsonEditors"
          @jsondataConFig="jsondataConFig"
        />
        <JsonEditor
          ref="jsonEditor"
          v-model="jsonData1"
          class="JsonEditor"
          @updataValue="updataValue"
          @changed="changed"
        />
      </div>
      <el-form
        ref="addForm"
        :model="addForm"
        label-width="80px"
        size="small"
        :rules="rules"
        :inline="true"
        class="forms"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" clearable />
        </el-form-item>
        <el-form-item label="租户" prop="tenantId">
          <el-select
            v-model="addForm.tenantId"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option
              :label="item.name"
              v-for="item in tenantList"
              :value="item.id"
              :key="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select
            v-model="addForm.type"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input type="input" v-model="addForm.version" clearable />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="addForm.remark" clearable />
        </el-form-item>
      </el-form>
      <div class="editor-button" style="margin-top: 1px">
        <el-button type="success" size="mini" @click="submit">{{
          submitTitle
        }}</el-button>
        <!-- <el-button type="danger" size="mini">取消</el-button> -->
      </div>
    </div>
  </div>
</template>
<script>
import JsonEditors from "@/components/JsonEditors";
import JsonEditor from "@/components/JsonEditor";
import ElementJson from "@/components/JsonEditors/elementJson.vue";
import * as tenantApi from "@/api/sys/tenant";
import { savaJson, checkJson, updateJson } from "@/api/link/file";

export default {
  data() {
    return {
      submitTitle: "新增JSON配置",
      tenantList: [],
      typeOptions: [
        {
          value: "2",
          label: "配置文件",
        },
      ],
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        version: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        tenantId: [
          { required: true, message: "必须选择租户", trigger: "change" },
        ],
      },
      addForm: {},
      jsonData: {
        CheckCode: {
          type: "string",
          default: "G98G7S9DF87GSDFG90S87FG09",
        },
        Module_2G4: {
          type: "object",
          properties: {
            WorkTime: {
              type: "string",
              default: "模块激活工作时间",
            },
            StandbyTime: {
              type: "string",
              default: "模块睡眠待机时间",
            },
            RecvBuf_Length: {
              type: "string",
              default: "模块接收buff长度",
            },
            RF_reference: {
              type: "object",
              properties: {
                Address: {
                  type: "string",
                  default: "射频通信地址(客户编码)",
                },
                ReferenceChannel: {
                  type: "string",
                  default: "射频基准频道(传感器/固定资产)",
                },
                DataRate: {
                  type: "string",
                  default: "射频数据速率",
                },
                OperatingPower: {
                  type: "string",
                  default: "射频工作功率",
                },
                WorkChannel: {
                  type: "string",
                  default: "射频工作频道",
                },
                RouteGroup: {
                  type: "string",
                  default: "射频路由分组",
                },
              },
            },
          },
        },
        Module_RS485: {
          type: "object",
          properties: {
            Master: {
              type: "object",
              properties: {
                Addr: {
                  type: "string",
                  default: "0",
                },
                Binding_Table: {
                  type: "array",
                  format: "select",
                  id: "arr_item",
                  title: "Binding_Table",
                  uniqueItems: true,
                  items: {
                    type: "object",
                    title: " ",
                    properties: {
                      DeviceID: {
                        type: "string",
                      },
                      RegisterAddr: {
                        type: "string",
                      },
                      RegisterCount: {
                        type: "string",
                      },
                    },
                  },
                  default: [
                    {
                      DeviceID: "0012345678",
                      RegisterAddr: "0",
                      RegisterCount: "1",
                    },
                    {
                      DeviceID: "0012345679",
                      RegisterAddr: "1",
                      RegisterCount: "2",
                    },
                  ],
                },
              },
            },
            Slave: {
              type: "object",
              properties: {
                Addr: {
                  type: "string",
                  default: "0",
                },
                Binding_Table: {
                  type: "array",
                  format: "select",
                  title: "Binding_Table",
                  uniqueItems: true,
                  items: {
                    type: "object",
                    title: " ",
                    id: "items",
                    properties: {
                      DeviceID: {
                        type: "string",
                      },
                      RegisterAddr: {
                        type: "string",
                      },
                      RegisterCount: {
                        type: "string",
                      },
                    },
                  },
                  default: [
                    {
                      DeviceID: "44",
                      RegisterAddr: "0",
                      RegisterCount: "1",
                    },
                    {
                      DeviceID: "55",
                      RegisterAddr: "1",
                      RegisterCount: "2",
                    },
                    {
                      DeviceID: "66",
                      RegisterAddr: "1",
                      RegisterCount: "2",
                    },
                  ],
                },
              },
            },
          },
        },
      },

      jsonData1: {},
    };
  },
  computed: {},
  mounted() {
    this.getTenantList();
    if (this.$route.query.id) {
      let id = this.$route.query.id;
      this.submitTitle = "修改JSON配置";
      console.log(id);
      checkJson(id).then((res) => {
        // console.log(res);
        let data = res.data;
        if (res.code == "200") {
          this.addForm = {
            name: data.name,
            remark: data.remark,
            tenantId: data.tenantId,
            type: data.type.toString(),
            version: data.version,
          };
          // this.jsonData = JSON.parse(data.dataFormat);
          this.jsonData1 = JSON.parse(data.dataJson);
          this.updataValue(JSON.parse(data.dataJson));
        }
      });
    }
  },
  components: {
    JsonEditors,
    JsonEditor,
    ElementJson,
  },
  watch: {},
  methods: {
    jsondataConFig(val) {
      this.jsonData1 = val;
    },
    submit() {
      console.log(this.$refs.elementJson.$refs.vueForm);
      this.$refs.elementJson.$refs.vueForm.$children[0].validate((valid) => {});
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (this.$route.query.id) {
            this.update();
          } else {
            this.save();
          }
        }
      });
    },
    update() {
      let dataJson = this.jsonData1;
      let dataFormat =  this.$refs.elementJson.formData
      let data = {
        id: this.$route.query.id,
        name: this.addForm.name,
        type: this.addForm.type,
        tenantId: this.addForm.tenantId,
        version: this.addForm.version,
        remark: this.addForm.remark,
        dataJson,
        dataFormat: JSON.stringify(dataFormat),
      };
      updateJson(data).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          this.$router.push({ path: "/fileCente" });
        }
      });
    },
    save() {
      let dataJson = this.jsonData1;
      let dataFormat = this.$refs.elementJson.formData
      let data = {
        name: this.addForm.name + ".json",
        type: this.addForm.type,
        tenantId: this.addForm.tenantId,
        version: this.addForm.version,
        remark: this.addForm.remark,
        dataJson,
        dataFormat: JSON.stringify(dataFormat),
      };
      savaJson(data).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "保存成功",
          });
          this.$router.push({ path: "/fileCente" });
        }
      });
    },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then((res) => {
        this.tenantList = res.data;
      });
    },
    changes(v) {
      // console.log(9898);
    },
    updataValue(val) {
        this.$refs.elementJson.formData = val
    },
    changed(val){
        // console.log(val)
        // this.$refs.elementJson.formData = JSON.parse(val)
    },
    upDatas(val) {
      // console.log(val);
      if (val !== undefined) this.jsonData1 = JSON.parse(JSON.stringify(val));
      //   console.log(JSON.stringify(this.jsonData1), "==========");
    },
  },
};
</script>
<style lang="scss" scoped>
.pratice {
  padding: 20px;
  .mains_contain {
    .mains_contains {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
    }
    width: 100%;
    .JsonEditors {
      width: 55%;
    }
    .JsonEditor {
      flex: 1;
      margin-left: 50px;
      max-height: calc(100vh - 250px);
      overflow-y: scroll;
    }
    .forms {
      margin-top: 30px;
    }
  }
}
</style>
